import type { Theme, SxProps, Breakpoint } from '@mui/material/styles';

import { useEffect, useState } from 'react';
import { varAlpha } from 'minimal-shared/utils';

import Box from '@mui/material/Box';
import ListItem from '@mui/material/ListItem';
import Collapse from '@mui/material/Collapse';
import { useTheme } from '@mui/material/styles';
import ListItemButton from '@mui/material/ListItemButton';
import Drawer, { drawerClasses } from '@mui/material/Drawer';

import { usePathname } from 'src/routes/hooks';
import { RouterLink } from 'src/routes/components';

import { Logo } from 'src/components/logo';
import { Iconify } from 'src/components/iconify';
import { Scrollbar } from 'src/components/scrollbar';

import { NavUpgrade } from '../components/nav-upgrade';
import { WorkspacesPopover } from '../components/workspaces-popover';

import type { NavItem } from '../nav-config-dashboard';
import type { WorkspacesPopoverProps } from '../components/workspaces-popover';

// ----------------------------------------------------------------------

export type NavContentProps = {
  data: NavItem[];
  slots?: {
    topArea?: React.ReactNode;
    bottomArea?: React.ReactNode;
  };
  workspaces: WorkspacesPopoverProps['data'];
  sx?: SxProps<Theme>;
};

/**
 * 递归渲染单个导航项，支持二级与三级菜单展开/收起。
 */
function NavItemNode({ item, pathname, level = 0 }: { item: NavItem; pathname: string; level?: number }) {
  const theme = useTheme();
  const hasChildren = Array.isArray(item.children) && item.children.length > 0;

  const isLeafActived = !!item.path && item.path === pathname;
  const isChildActived = hasChildren ? item.children!.some((child) => matchPathRecursive(child, pathname)) : false;

  const [open, setOpen] = useState<boolean>(isChildActived);
  const paddingLeft = 2 + level * 2;

  const buttonSx = [
    (muiTheme: Theme) => ({
      pl: paddingLeft,
      py: 1,
      gap: 2,
      pr: 1.5,
      borderRadius: 0.75,
      typography: 'body2',
      fontWeight: 'fontWeightMedium',
      color: muiTheme.vars.palette.text.secondary,
      minHeight: 44,
      ...(isLeafActived || isChildActived
        ? {
          fontWeight: 'fontWeightSemiBold',
          color: muiTheme.vars.palette.primary.main,
          bgcolor: varAlpha(muiTheme.vars.palette.primary.mainChannel, 0.08),
          '&:hover': {
            bgcolor: varAlpha(muiTheme.vars.palette.primary.mainChannel, 0.16),
          },
        }
        : {}),
    }),
  ];

  const handleToggle = () => setOpen((prev) => !prev);

  return (
    <>
      <ListItem disableGutters disablePadding key={item.title}>
        <ListItemButton
          disableGutters
          component={hasChildren || !item.path ? 'div' : RouterLink}
          href={hasChildren || !item.path ? undefined : item.path}
          onClick={hasChildren ? handleToggle : undefined}
          sx={buttonSx}
        >
          <Box component="span" sx={{ width: 24, height: 24 }}>
            {item.icon}
          </Box>

          <Box component="span" sx={{ flexGrow: 1 }}>
            {item.title}
          </Box>

          {hasChildren ? (
            <Iconify width={18} icon="carbon:chevron-sort" sx={{ color: 'text.disabled' }} />
          ) : (
            item.info && item.info
          )}
        </ListItemButton>
      </ListItem>

      {hasChildren && (
        <Collapse in={open} unmountOnExit>
          <Box component="ul" sx={{ display: 'flex', flexDirection: 'column', gap: 0.5 }}>
            {item.children!.map((child) => (
              <NavItemNode key={child.title} item={child} pathname={pathname} level={level + 1} />
            ))}
          </Box>
        </Collapse>
      )}
    </>
  );
}

/**
 * 递归判断某个导航项（及其子项）是否与当前路径匹配。
 */
function matchPathRecursive(node: NavItem, pathname: string): boolean {
  if (node.path && node.path === pathname) return true;
  if (node.children && node.children.length > 0) {
    return node.children.some((child) => matchPathRecursive(child, pathname));
  }
  return false;
}

export function NavDesktop({
  sx,
  data,
  slots,
  workspaces,
  layoutQuery,
}: NavContentProps & { layoutQuery: Breakpoint }) {
  const theme = useTheme();

  return (
    <Box
      sx={{
        pt: 2.5,
        px: 2.5,
        top: 0,
        left: 0,
        height: 1,
        display: 'none',
        position: 'fixed',
        flexDirection: 'column',
        zIndex: 'var(--layout-nav-zIndex)',
        width: 'var(--layout-nav-vertical-width)',
        borderRight: `1px solid ${varAlpha(theme.vars.palette.grey['500Channel'], 0.12)}`,
        [theme.breakpoints.up(layoutQuery)]: {
          display: 'flex',
        },
        ...sx,
      }}
    >
      <NavContent data={data} slots={slots} workspaces={workspaces} />
    </Box>
  );
}

// ----------------------------------------------------------------------

export function NavMobile({
  sx,
  data,
  open,
  slots,
  onClose,
  workspaces,
}: NavContentProps & { open: boolean; onClose: () => void }) {
  const pathname = usePathname();

  useEffect(() => {
    if (open) {
      onClose();
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [pathname]);

  return (
    <Drawer
      open={open}
      onClose={onClose}
      sx={{
        [`& .${drawerClasses.paper}`]: {
          pt: 2.5,
          px: 2.5,
          overflow: 'unset',
          width: 'var(--layout-nav-mobile-width)',
          ...sx,
        },
      }}
    >
      <NavContent data={data} slots={slots} workspaces={workspaces} />
    </Drawer>
  );
}

// ----------------------------------------------------------------------

/**
 * 导航内容容器：渲染 Logo、工作空间切换以及左侧菜单。
 */
export function NavContent({ data, slots, workspaces, sx }: NavContentProps) {
  const pathname = usePathname();

  return (
    <>
      <Logo />

      {slots?.topArea}

      {/* <WorkspacesPopover data={workspaces} sx={{ my: 2 }} /> */}

      <Scrollbar fillContent style={{ marginTop: 24 }}>
        <Box
          component="nav"
          sx={[
            {
              display: 'flex',
              flex: '1 1 auto',
              flexDirection: 'column',
            },
            ...(Array.isArray(sx) ? sx : [sx]),
          ]}
        >
          <Box component="ul" sx={{ gap: 0.5, display: 'flex', flexDirection: 'column' }}>
            {data.map((item) => (
              <NavItemNode key={item.title} item={item} pathname={pathname} />
            ))}
          </Box>
        </Box>
      </Scrollbar>

      {slots?.bottomArea}
    </>
  );
}
